package com.fjwt.gz.coupon.hkpay.hkpayutil;

import net.sf.json.JSONArray;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.MessageDigest;
import java.util.*;

public class HkSignUtil {

    private static BouncyCastleProvider provider = new BouncyCastleProvider();

    /**
     * 直接拼接key在最后面
     * 例：key=123456789的时候待签名的字符串为，aa=3&bb=1&cc=1&dd=20160426999123456789
     * @param partnerKey
     * @param params
     * @return
     */
    public  static String signParams(String partnerKey, Map params){
        //直接拼接key
        String tobesign = getToBeSign(params) + partnerKey;
        return md5dataToSign(tobesign);
    }


    public static String md5dataToSign(String data){
        String algorithm = "MD5";
        try {
            //BouncyCastleProvider provider = new BouncyCastleProvider();
            MessageDigest md = MessageDigest.getInstance(algorithm, provider);
            byte[] rtn = md.digest(data.getBytes("UTF-8"));
            return byte2Hex(rtn).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("不支持的算法:"+algorithm);
        }
    }

    public static String getToBeSign(Map params){
        TreeMap tm = new TreeMap();
        tm.putAll(params); //参数排序
        Set set = tm.entrySet();
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (Iterator iterator = set.iterator(); iterator.hasNext();) {
            Map.Entry e = (Map.Entry) iterator.next();
            String k = (String)e.getKey();
//			String v = (String)e.getValue();
            if(e.getValue() == null || "".equals(e.getValue()) || "sign".equals(k) || "mac".equals(k)){
                continue;
            }
            String v = "";
            if(e.getValue() instanceof JSONArray){
                v = getJsonArrayStr((JSONArray)e.getValue());
            }else if(e.getValue() instanceof net.sf.json.JSONObject){
                v = getToBeSign((net.sf.json.JSONObject)e.getValue());
            }else if(e.getValue() instanceof com.alibaba.fastjson2.JSONObject){
                v = getToBeSign((com.alibaba.fastjson2.JSONObject)e.getValue());
            }else{
                v = e.getValue().toString();
            }
            if(i != 0){
                sb.append("&");
            }
            sb.append(k+"="+v);
            i = i + 1;
        }
        return sb.toString();
    }

    public static String getJsonArrayStr(JSONArray a){
        String r = "";
        for(int j=0; j < a.size() ; j++){
            Object b = (Object) a.get(j);
            String v = "";
            if(b instanceof JSONArray){
                v = getJsonArrayStr((JSONArray)b);
            }else if(b instanceof net.sf.json.JSONObject){
                v = getToBeSign((net.sf.json.JSONObject)b);
            }else{
                v = b.toString();
            }
            if(j ==0){
                r = v;
            }else{
                r += "&" + v;
            }
        }
        return r;
    }

    public static String byte2Hex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                sb.append("0").append(stmp);
            } else {
                sb.append(stmp);
            }
        }
        return sb.toString().toUpperCase();
    }

    // 测试环境参数加密
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("accessid", "cpostest");
        map.put("redirect_url", "https://www.myurl/aaaa/bbbb");
        map.put("appid", "wx17728c1a8fa300d6");
        System.out.println(signParams("48e70b51cab84019a2dddf2f03f13a38", map));
    }
}
